package cn.lj.common.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Description: WebSecurityConfg配置文件
 * @author: lijie
 * @date: 2021年07月23日 下午 08:04:53
 */
@Configuration
@EnableWebSecurity//启用springSecurity
////拦截注解@PreAuthorize配置
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfg extends WebSecurityConfigurerAdapter {
    /**
     * 功能描述: 注入加密算法
     *
     * @auther: lijie
     * @date: 2021/7/24 上午 10:09:56
     * @return: org.springframework.security.crypto.password.PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 功能描述: 认证
     * @auther: lijie
     * @param auth:
     * @date: 2021/7/24 下午 04:30:45
     * @return: void
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置能登录的用户
        auth.inMemoryAuthentication()
                //指定账户
                .withUser("admin")
                //使用加密算法指定密码
                .password(passwordEncoder().encode("123456"))
                .roles("admin")
                .and()
                .withUser("root")
                //使用加密算法指定密码
                .password(passwordEncoder().encode("root"))
                .roles("root").and();
    }
    /**
     * 功能描述: 授权
     * @auther: lijie
     * @param http:
     * @date: 2021/7/24 下午 04:30:53
     * @return: void
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //设置方法权限
        http.authorizeRequests()
                .antMatchers("/login/inlogin").permitAll()
                .antMatchers("/login/inloginyzm").hasRole("admin")
                .antMatchers("/login/inloginnumber").hasRole("root");

        //开启登录功能
        //指定登录页面
        //.loginPage("")
        http.formLogin();
        //http.formLogin().loginPage("");
        //开启注销功能
        http.logout().logoutSuccessUrl("/login/inlogin");
        //生成token
        http.rememberMe();
    }
}
